package com.mrtaohuan.action;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.google.inject.Inject;
import com.mrtaohuan.render.HttpContext;
import com.mrtaohuan.render.freemarker.AbstractFreeMarkerRender;
import com.mrtaohuan.render.freemarker.FreeMarkerRenderer;
import com.mrtaohuan.render.freemarker.Templates;

@Path("/")
public class Index {

	@Inject
	HttpContext context;

	@GET
	@Produces(MediaType.TEXT_HTML)
	public String index() {
		final AbstractFreeMarkerRender renderer = new FreeMarkerRenderer();
		renderer.setTemplateName("index");
		renderer.setContext(context);
		return renderer.renderHtml();
	}
	
	@GET
	@Path("/bingImg")
	@Produces({MediaType.APPLICATION_JSON})
	public String bingImg() throws Exception {

		URL url = new URL(
				"http://cn.bing.com/HPImageArchive.aspx?format=js&idx=1&n=1&nc="+System.currentTimeMillis()+"&video=1");
		HttpURLConnection httpURLConnection = (HttpURLConnection) url
				.openConnection();
		httpURLConnection.setRequestMethod("GET");
		httpURLConnection.setConnectTimeout(5000);
		InputStream inputStream = httpURLConnection.getInputStream();
		byte[] data = readInputStream(inputStream);
		String html = new String(data,"UTF-8");
		
		inputStream.close();
		return html;
	}

	public byte[] readInputStream(InputStream inSream) throws Exception {
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inSream.read(buffer)) != -1) {
			byteArrayOutputStream.write(buffer, 0, len);
		}
		inSream.close();
		return byteArrayOutputStream.toByteArray();
	}
	
}
